package com.ruoyi.web.product;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.StockLog;
import com.ruoyi.common.enums.ReasonType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.product.domain.Recommend;
import com.ruoyi.product.domain.UserPro;
import com.ruoyi.product.domain.vo.ProCatVo;
import com.ruoyi.product.service.ICategoriesService;
import com.ruoyi.product.service.IRecommendService;
import com.ruoyi.product.service.IUserProService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.product.domain.Products;
import com.ruoyi.product.service.IProductsService;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 商品列表Controller
 *
 * @author jtm
 * @date 2024-12-07
 */
@RestController
@RequestMapping("/product/products")
public class ProductsController extends BaseController
{
    @Autowired
    private IProductsService productsService;

    @Autowired
    private ICategoriesService categoriesService;

    @Autowired
    private IUserProService proService;

    @Autowired
    private IRecommendService recommendService;

    /**
     * 查询商品列表列表
     */
    @PreAuthorize("@ss.hasPermi('product:products:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProCatVo proCatVo)
    {
        startPage();
//        账号是超级管理员或普通管理员
            List<ProCatVo> list = productsService.selectProductsList(proCatVo);
            return getDataTable(list);
//        List<Products> list = productsService.selectProductsList(products);
//        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('product:products:list')")
    @GetMapping("/ulist")
    public TableDataInfo ulist(ProCatVo proCatVo){
        startPage();
        //  账号是卖家 查询自己的商品信息
        List<ProCatVo> list = productsService.selectUserProductsList(proCatVo);
        return getDataTable(list);
    }

    /**
     * 导出商品列表列表
     */
//    @PreAuthorize("@ss.hasPermi('product:products:export')")
//    @Log(title = "商品列表", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Products products)
//    {
//        List<Products> list = productsService.selectProductsList(products);
//        ExcelUtil<Products> util = new ExcelUtil<Products>(Products.class);
//        util.exportExcel(response, list, "商品列表数据");
//    }


    /**
     * 获取商品列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:products:query')")
    @GetMapping("/{pId}")
    public AjaxResult getInfo(@PathVariable("pId") Long pId)
    {
        System.out.println(pId);
        ProCatVo proCatVo = productsService.selectProductsById(pId);
        return AjaxResult.success(proCatVo);
    }

    /**
     * 新增商品列表
     */
    @PreAuthorize("@ss.hasPermi('product:products:add')")
    @Log(title = "商品列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProCatVo proCatVo)
    {
        Products products = new Products();
        String cName = proCatVo.getcName();
        Long cId = categoriesService.selectCId(cName);
        products.setcId(cId);
        products.setName(proCatVo.getpName());
        products.setImage(proCatVo.getImage());
        products.setDescription(proCatVo.getDescription());
        products.setNewPrice(proCatVo.getNewPrice());
//        刚创建默认销量为0
        products.setSaleVolum(proCatVo.getSaleVolum());
        products.setStock(proCatVo.getStock());
        products.setCreatedTime(DateUtils.getNowDate());
        products.setUpdatedTime(DateUtils.getNowDate());
        products.setType(0L);
        UserPro userPro = new UserPro();
        userPro.setUserId(proCatVo.getUserId());
        productsService.insertProducts(products);
        userPro.setProId(products.getId());
        return toAjax(proService.insertUserPro(userPro));
    }

    /**
     * 修改商品列表
     */
    @PreAuthorize("@ss.hasPermi('product:products:edit')")
    @Log(title = "商品列表", businessType = BusinessType.UPDATE)
    @StockLog(reason = ReasonType.SELLER_UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProCatVo proCatVo)
    {
        Products products = productsService.selectProductById(proCatVo.getpId());
        products.setUpdatedTime(DateUtils.getNowDate());
        products.setImage(products.getImage());
//        把之前的new_price封装到现在的old_price字段中
        products.setOldPrice(products.getNewPrice());
        products.setNewPrice(proCatVo.getNewPrice());
        products.setDescription(proCatVo.getDescription());
        products.setName(proCatVo.getpName());
        Long cId = categoriesService.selectCId(proCatVo.getcName());
        products.setcId(cId);
        products.setStock(proCatVo.getStock());
        return toAjax(productsService.updateProducts(products));
    }

    /**
     * 删除商品列表
     */
    @PreAuthorize("@ss.hasPermi('product:products:remove')")
    @Log(title = "商品列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{pId}")
    public AjaxResult remove(@PathVariable Long[] pId)
    {
        proService.deleteUserProByProIds(pId);
        return toAjax(productsService.deleteProductsByIds(pId));
    }

    @PreAuthorize("@ss.hasPermi('product:products:recommend')")
    @Log(title = "推荐", businessType = BusinessType.INSERT)
    @PostMapping("/recommend/{pId}")
    public AjaxResult recommendProduct(@PathVariable("pId") Long pId){
//        Products products = productsService.selectProductById(pId);
//        Long userId = proService.selectUserIdByProId(pId);
        Recommend recommend = recommendService.selectRecommendByProId(pId);
//        如果recommend表中没有该商品
        if (recommend == null){
            Recommend recommend1 = new Recommend();
            recommend1.setRecommend(1L);
            recommend1.setUserId(proService.selectUserIdByProId(pId));
            recommend1.setProId(pId);
            recommend1.setUpdatedTime(DateUtils.getNowDate());
            recommend1.setCreatedTime(DateUtils.getNowDate());
            return toAjax(recommendService.insertRecommend(recommend1));
        }else{
//            如果有但是已经被取消推荐
            if (recommend.getRecommend() != 1L){
                recommend.setRecommend(1L);
                recommend.setUpdatedTime(DateUtils.getNowDate());
                return toAjax(recommendService.updateRecommend(recommend));
            }
        }
        return null;
    }
}
